﻿using Surpass.Model.BaseDomain;
using Surpass.Model.Dto.ResponseDto.ResponseModel.ResponseDept;
using Surpass.Model.Dto.ResponseDto.ResponseModel.ResultModel;
using Surpass.Model.SysDomain;
using Surpass.Repository.IRepository;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Surpass.Repository.Repository
{
    public class SysDeptRepository : DataBase, ISysDeptRepository
    {
        private readonly SurpassDbContext _surpassDbContext;
        public SysDeptRepository(SurpassDbContext surpassDbContext) :base(surpassDbContext)
        {
            _surpassDbContext = surpassDbContext;
        }
        /// <summary>
        /// 获取所有部门
        /// </summary>
        /// <returns></returns>
        public dynamic GetDeptAll()
        {
            //var list = LoadEntities<SysDept>().Where(u=>u.Deleted==false).ToList();
            var query = from a in _surpassDbContext.SysDept
                        join b in _surpassDbContext.SysUsers
                        on a.UserId equals b.UserId
                        where b.Deleted ==false
                        select new DeptResponse
                        {
                            DId = a.DId,
                            DName = a.DName,
                            ParentId = a.ParentId,
                            LeadName = b.NickName
                        };
            return GetDepts(query.ToList());
        }
        /// <summary>
        /// 部门递归
        /// </summary>
        /// <param name="sysDepts"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public List<DeptResponse> GetDepts(List<DeptResponse> sysDepts,int parentId=0)
        {
            return sysDepts.Where(u=>u.ParentId==parentId).Select(u => new DeptResponse
            {
                DId = u.DId,
                DName = u.DName,
                ParentId = u.ParentId,
                LeadName = u.LeadName,
                ChildDepts = GetDepts(sysDepts, u.DId).Count==0?null: GetDepts(sysDepts, u.DId)
            }).ToList();
        }
    }
}
